package cool.mtc.core.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author 明河
 */
public abstract class FileUtil {

    /**
     * 生成文件
     */
    public static File generateFile(String path) throws IOException {
        Path filePath = Paths.get(path);
        // 创建目录
        if (Files.notExists(filePath.getParent())) {
            Files.createDirectories(filePath.getParent());
        }
        // 创建文件
        if (Files.notExists(filePath)) {
            Files.createFile(filePath);
        }
        return filePath.toFile();
    }

    /**
     * 确保文件是存在的，如果不存在则创建文件
     */
    public static File ensureFileExist(String path) throws IOException {
        File file = new File(path);
        if (file.exists()) {
            return file;
        }
        return generateFile(path);
    }

    /**
     * 读取文件内容
     */
    public static String readString(String path) throws IOException {
        return readString(Paths.get(path));
    }

    public static String readString(File file) throws IOException {
        return readString(file.toPath());
    }

    public static String readString(Path path) throws IOException {
        List<String> stringList = Files.readAllLines(path);
        StringBuilder content = new StringBuilder();
        stringList.forEach(item -> content.append(item).append("\r\n"));
        return content.toString();
    }
}
